package com.bamboo.toolbox.core.utils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;

/**
 * json工具类
 *
 * @author 陆志庆
 * @version 1.0
 * @date 2017年5月25日
 */
public class JsonUtils {
    private final static ObjectMapper JSON_MAPPER = new ObjectMapper();

    static {
        JsonUtils.JSON_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonUtils.JSON_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    public static String toJson(Object data) {
        try {
            return JSON_MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json序列化异常", e);
        }
    }

    public static <T> T toObject(String json, Class<T> clz) {
        try {
            return JSON_MAPPER.readValue(json.getBytes(), clz);
        } catch (JsonParseException e) {
            throw new RuntimeException("json转换异常:" + json, e);
        } catch (JsonMappingException e) {
            throw new RuntimeException("json映射异常:" + json, e);
        } catch (IOException e) {
            throw new RuntimeException("jsonI/O异常:" + json, e);
        }
    }

    public static <T> T toObject(String json, TypeReference<T> typeRef) {
        try {
            return JSON_MAPPER.readValue(json.getBytes(), typeRef);
        } catch (JsonParseException e) {
            throw new RuntimeException("json转换异常:" + json, e);
        } catch (JsonMappingException e) {
            throw new RuntimeException("json映射异常:" + json, e);
        } catch (IOException e) {
            throw new RuntimeException("jsonI/O异常:" + json, e);
        }
    }

    public static String format(String json) {
        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(jsonObject);
    }
}
